package com.yueshop.cart.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yueshop.cart.feign.ProductFeignService;
import com.yueshop.cart.interceptor.CartInterceptor;
import com.yueshop.cart.service.CartService;
import com.yueshop.cart.vo.Cart;
import com.yueshop.cart.vo.CartItem;
import com.yueshop.cart.vo.SkuInfoVo;
import com.yueshop.cart.vo.UserInfoTo;
import com.yueshop.common.constant.CartConstant;

import com.yueshop.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    ThreadPoolExecutor executor;

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        //购物车添加操作
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String  str = (String) cartOps.get(skuId.toString());

        if(StringUtils.isEmpty(str)){
            //如果商品skuid 查询的 商品是空 添加操作
            CartItem cartItem = new CartItem();


            CompletableFuture<Void> skuInfoFuture = CompletableFuture.runAsync(() -> {
                R r = productFeignService.info(skuId);

                SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setSkuId(skuId);
                cartItem.setCount(num);
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setCheck(true);
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setPrice(skuInfo.getPrice());
            }, executor);

            //远程查询销售属性组合
            CompletableFuture<Void> skuSaleAttrFuture = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            }, executor);

            CompletableFuture.allOf(skuInfoFuture, skuSaleAttrFuture).get();

            //将商品信息 转为json数据 放入到redis中
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }else{
            //如果不为空 就说明 商品已经存在, 需要在原来数量上+ 新的数量 再保存到redis中
            //将查询到的商品字符串转为对象
            CartItem cartItem = JSON.parseObject(str, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String cartItem  = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(cartItem,CartItem.class);
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        //判断用户是否登录
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()!=null){
            //已经登陆
            //先获取临时购物车属性, 如果有  将他 合并到 登录的购物车
           String userKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
           String tempUserKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();

            List<CartItem> tempCartItems = getCartItems(tempUserKey);
            if(tempCartItems!=null&&tempCartItems.size()>0){
                for (CartItem tempCartItem : tempCartItems) {

                    addToCart(tempCartItem.getSkuId(),tempCartItem.getCount());
                }//清空临时购物车
                stringRedisTemplate.delete(tempUserKey);
            }

            List<CartItem> cartItems = getCartItems(userKey);
            cart.setItems(cartItems);
        }else {
            //未登录
            List<CartItem> cartItems = getCartItems(CartConstant.CART_PREFIX + userInfoTo.getUserKey());
            cart.setItems(cartItems);
        }
        return cart;
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        //获取当前登录或者未登录的购物车
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        //获取当前登录或者未登录的购物车
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        //获取当前登录或者未登录的购物车
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getCheckedItem() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //判断用户是否登录
        if(userInfoTo.getUserId()==null){//未登录
            return null;
        }else {//以登录
            String cartKey= CartConstant.CART_PREFIX+userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            List<CartItem> collect = cartItems.stream().filter(item->item.getCheck()).map(cartItem ->{
                        //远程调用查询商品的最新价格并进行更新
                R price = productFeignService.getPrice(cartItem.getSkuId());
                String data = (String) price.get("data");
                cartItem.setPrice(new BigDecimal(data));
           return cartItem;
           }).collect(Collectors.toList());
            return collect;
        }
    }

    //获取登录或者未登录用户购物车 所有购物项信息
    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> ops = stringRedisTemplate.boundHashOps(cartKey);

        List<Object> values = ops.values();
        if(values!=null&&values.size()>0) {
            List<CartItem> collect = values.stream().map(item -> {
                String itemStr = (String) item;
                return JSON.parseObject(itemStr, CartItem.class);
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }





    //获取要操作的购物车
    private BoundHashOperations<String, Object, Object> getCartOps() {
        //添加购物车数据 判断 用户是否登录 hash
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey="";
        if(userInfoTo.getUserId()!=null) {//已经登录
            //yueshop:cart:4
            cartKey = CartConstant.CART_PREFIX+userInfoTo.getUserId();
        }else{
            //临时用户 yueshop:cart:userkey
            cartKey = CartConstant.CART_PREFIX+userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> hashOperations = stringRedisTemplate.boundHashOps(cartKey);
        return hashOperations;
    }
}
